package cj.web.admin.util;

import java.text.DecimalFormat;
import java.util.Random;

public class StringRandom {  
	  
    //生成随机数字和字母,  
    public static String getStringRandom(int length) {  
          
        String val = "";  
        Random random = new Random();  
          
        //参数length，表示生成几位随机数  
        for(int i = 0; i < length; i++) {  
              
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
            //输出字母还是数字  
            if( "char".equalsIgnoreCase(charOrNum) ) {  
                //输出是大写字母还是小写字母  
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;  
                val += (char)(random.nextInt(26) + temp);  
            } else if( "num".equalsIgnoreCase(charOrNum) ) {  
                val += String.valueOf(random.nextInt(10));  
            }  
        }  
        return val;  
    } 
    
    /**
     * 产生4位随机数(0000-9999)
     * @return 4位随机数
     */
    public static String getFourRandom(){
        Random random = new Random();
        String fourRandom = random.nextInt(10000) + "";
        int randLength = fourRandom.length();
        if(randLength<4){
          for(int i=1; i<=4-randLength; i++)
              fourRandom = "0" + fourRandom  ;
      }
        return fourRandom;
    }
    
    /**
     * 产生4位随机数(000000-999999)
     * @return 4位随机数
     */
    public static String getSixRandom(){
        Random random = new Random();
        String fourRandom = random.nextInt(1000000) + "";
        int randLength = fourRandom.length();
        if(randLength<6){
          for(int i=1; i<=6-randLength; i++)
              fourRandom = "0" + fourRandom  ;
      }
        return fourRandom;
    }
    
    public static String formatNum(String formatStr,int num){
    	DecimalFormat decimalFormat = new DecimalFormat(formatStr);
        String numFormatStr = decimalFormat.format(num);
		return numFormatStr;
    }
      
    public static void  main(String[] args) {  
        StringRandom test = new StringRandom();  
        //测试  
//        System.out.println("8位数字加符号=="+test.getStringRandom(8));  
        
        for(int i=0;i<100;i++){
        	System.out.println("6位数字=="+test.getSixRandom()+"===size:"+test.getSixRandom().length());
        }
//        System.out.println(test.formatNum("0000", 1));   
    }  
}
